/**
 * 用户信息管理实现类
 */
package com.bys.ots.service.impl;

import com.alibaba.fastjson.JSON;
import com.bys.ots.config.wx.WxConfig;
import com.bys.ots.config.wx.WxTokenUpdate;
import com.bys.ots.dao.EmailMapper;
import com.bys.ots.dao.UserMapper;
import com.bys.ots.model.Email;
import com.bys.ots.model.User;
import com.bys.ots.pojo.Result;
import com.bys.ots.pojo.ResultEnum;
import com.bys.ots.pojo.ResultUtil;
import com.bys.ots.service.UserService;
import com.bys.ots.util.RedisWrapUtil;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author bairuihua
 * 2019/11/26
 */
@Service(value = "userService")
public class UserServiceImpl implements UserService
{
    private final Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);

    @Resource
    private UserMapper userMapper;

    @Resource
    private EmailMapper emailMapper;

    @Autowired
    RedisWrapUtil redisWrapUtil;

    @Autowired
    WxConfig wxConfig;

    @Autowired
    WxTokenUpdate wxTokenUpdate;

    @Override
    public Result login(String rawData, HttpSession session)
    {
        if (StringUtils.isEmpty(rawData))
        {
            logger.error("->User start to login system error, the login info is：" + rawData);
            return ResultUtil.error(ResultEnum.CODE_409);
        }
        JSONObject jsonObj = JSONObject.fromObject(rawData);
        String openId = (String) jsonObj.get("rawData");
        if (StringUtils.isEmpty(openId))
        {
            logger.error("->The user login param is empty,openId: " + openId);
            return ResultUtil.error(ResultEnum.CODE_409);
        }
        User user = userMapper.findByOpenId(openId);
        if (null == user)
        {
            return ResultUtil.error(ResultEnum.CODE_412);
        }
        return ResultUtil.OTSResult(user.getUserId());
    }

    @Override
    public Result getCode(String code)
    {
        com.alibaba.fastjson.JSONObject re = null;
        try
        {
            if (StringUtils.isEmpty(code))
            {
                return ResultUtil.success();
            }
            String url = wxConfig.getWxLoginUrl();
            String appid = wxConfig.getAppId();
            String appsecret = wxConfig.getSecret();
            url = url.replace("APPID", appid);
            url = url.replace("SECRET", appsecret);
            url = url.replace("JSCODE", code);
            CloseableHttpClient httpClient = HttpClients.createDefault();
            String result = null;
            CloseableHttpResponse response = null;
            URIBuilder uriBuilder = new URIBuilder(url);
            HttpPost httpPost = new HttpPost(uriBuilder.build());
            httpPost.addHeader("Content-Type", "text/xml; charset=utf-8");
            httpPost.addHeader("Accept-Charset", "utf-8");
            response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            result = EntityUtils.toString(entity, "UTF-8");

            if (StringUtils.isNotEmpty(result))
            {
                re = JSON.parseObject(result);
                String openId = re.getString("openid");
                if (StringUtils.isEmpty(openId))
                {
                    logger.error("微信返回openId为空");
                    return ResultUtil.error(ResultEnum.CODE_429);
                }
 //               User user = userMapper.findByOpenId(openId);
//                if (ObjectUtils.isEmpty(user))
//                {
//                    logger.error("用户未注册");
//                    return ResultUtil.error(ResultEnum.CODE_412);
//                }
            }
            else
            {
                logger.error("接口没有返回任何信息");
                return ResultUtil.error(ResultEnum.CODE_428);
            }
        }
        catch (Exception e)
        {
            logger.error("调用微信接口codeSession异常");
            return ResultUtil.error(ResultEnum.CODE_427);
        }
        System.out.println(re.toJSONString());
        return ResultUtil.OTSResult(re);
    }

    @Override
    public Result getToken()
    {
        if (StringUtils.isEmpty(WxTokenUpdate.accessToken))
        {
            wxTokenUpdate.updateToken();
        }
        return ResultUtil.OTSResult(WxTokenUpdate.accessToken);
    }

    @Override
    public Result loginTest(String rawData, HttpSession session)
    {
        if (StringUtils.isEmpty(rawData))
        {
            logger.error("->User start to login system error, the login info is：" + rawData);
            return ResultUtil.error(ResultEnum.CODE_409);
        }
        JSONObject jsonObj = JSONObject.fromObject(rawData);
        String email = (String) jsonObj.get("email");
        String checkCode = (String) jsonObj.get("checkCode");
        // Redis验证码
        boolean bool = redisWrapUtil.check(email, checkCode);
        if (!bool)
        {
            return ResultUtil.error(ResultEnum.CODE_403);
        }
        // 判断用户是否已经存在
        List<Email> email1 = emailMapper.findByEmail(email);
        String userId = email1.get(0).getUserId();
        if (!ObjectUtils.isEmpty(userId))
        {
            logger.info("->登录成功, userId: " + userId);
            return ResultUtil.OTSResult(userId);
        }
        logger.info("->login param error: {}", userId);
        return ResultUtil.error(ResultEnum.CODE_404);

    }

    @Override
    public Result searchEmailList(String userId)
    {
        if (StringUtils.isEmpty(userId))
        {
            return ResultUtil.error(ResultEnum.CODE_409);
        }
        List<Email> emailList = emailMapper.findByUserId(userId);
        return ResultUtil.OTSResult(emailList);
    }

    @Override
    public Result addEmail(String rawData)
    {
        if (StringUtils.isEmpty(rawData))
        {
            return ResultUtil.error(ResultEnum.CODE_409);
        }
        JSONObject jsonObj = JSONObject.fromObject(rawData);

        String email = (String) jsonObj.get("email");
        String userId = (String) jsonObj.get("userId");
        String remark = (String) jsonObj.get("remark");
        String checkCode = (String) jsonObj.get("checkCode");
        if (StringUtils.isEmpty(email) || StringUtils.isEmpty(userId)
                || StringUtils.isEmpty(checkCode))
        {
            return ResultUtil.error(ResultEnum.CODE_404);
        }
        // Redis验证码
        boolean bool = redisWrapUtil.check(email, checkCode);
        if (!bool)
        {
            return ResultUtil.error(ResultEnum.CODE_403);
        }
        List<Email> emailEntity = emailMapper.findByEmail(email);
//        if (!ObjectUtils.isEmpty(emailEntity))
//        {
//            return ResultUtil.error(ResultEnum.CODE_425);
//        }
        List<Email> emailList = emailMapper.findByUserId(userId);
        for (Email emailEach : emailList)
        {
            if (emailEach.getEmail().equalsIgnoreCase(email))
            {
                logger.error("您已添加过改邮箱！userId：{},email:{}", userId, email);
                return ResultUtil.error(ResultEnum.CODE_431);
            }
        }
        if (StringUtils.equalsIgnoreCase("LSGCNreagentcs@thermofisher.onmicrosoft.com", email) ||
                StringUtils.equalsIgnoreCase("CSSH@thermofisher.com", email))
        {
            Boolean have = false;

            for (Email emailEach : emailList)
            {
                if (emailEach.getEmail().toLowerCase().contains("@thermofisher.com"))
                {
                    have = true;
                }
            }
            if (!have)
            {
                logger.error("没有权限！userId：{}", userId);
                return ResultUtil.error(ResultEnum.CODE_430);
            }
        }
        Email soEmail = new Email();
        String uuid = UUID.randomUUID().toString();
        soEmail.setId(uuid);
        soEmail.setUserId(userId);
        soEmail.setEmail(email);
        soEmail.setIsDeleted("0");
        soEmail.setRemark(remark);
        int i = emailMapper.insert(soEmail);
        if (i >= 1)
        {
            logger.info("->Add Email success: {}", soEmail);
            return ResultUtil.success();
        }

        return ResultUtil.error(ResultEnum.CODE_405);

    }

    @Override
    public Result register(String rawData, HttpSession session)
    {
        if (StringUtils.isEmpty(rawData))
        {
            logger.error("->User start to register system error, the register info is：" + rawData);
            return ResultUtil.error(ResultEnum.CODE_409);
        }
        JSONObject jsonObj = JSONObject.fromObject(rawData);
        String email = (String) jsonObj.get("emailAddress");
        String checkCode = (String) jsonObj.get("checkCode");
        String openId = (String) jsonObj.get("openId");
        if (StringUtils.isEmpty(email) || StringUtils.isEmpty(checkCode) ||
                StringUtils.isEmpty(openId))
        {
            logger.error("->The user register param is empty,email: " + email + " ,checkCode: " +
                                 checkCode + " ,openId: " + openId);
            return ResultUtil.error(ResultEnum.CODE_404);
        }
        // Redis验证码
        boolean bool = redisWrapUtil.check(email, checkCode);
        if (!bool)
        {
            return ResultUtil.error(ResultEnum.CODE_403);
        }

        // 判断用户是否已经存在
        User findUser = userMapper.findByOpenId(openId);
        if (!ObjectUtils.isEmpty(findUser))
        {
            logger.error("->该账号已被注册, email: " + openId);
            return ResultUtil.error(ResultEnum.CODE_405);
        }
        else
        {
            String uuid = UUID.randomUUID().toString();
            User newUser = new User();
            newUser.setUserId(uuid);
            newUser.setOpenId(openId);
            newUser.setIsDeleted(0);
            String uuid2 = UUID.randomUUID().toString();
            Email soEmail = new Email();
            soEmail.setUserId(uuid);
            soEmail.setId(uuid2);
            soEmail.setEmail(email);
            soEmail.setIsDeleted("0");
            int insertUser = userMapper.insertUser(newUser);
            int insertEmail = emailMapper.insert(soEmail);

            if (insertUser > 0 && insertEmail > 0)
            {
                logger.info("用户被成功创建：｛｝" + newUser);
                return ResultUtil.OTSResult(newUser.getUserId());
            }
            logger.error("->该账号注册失败, openId: " + openId);
            return ResultUtil.error(ResultEnum.CODE_421);
        }

    }

    @Override
    public Result deleteEmail(String rowData)
    {
        logger.info("->The user enter service deleteEmail param is rowData:{}", rowData);
        if (StringUtils.isEmpty(rowData))
        {
            logger.error("->rowDate error, the request info is：" + rowData);
            return ResultUtil.error(ResultEnum.CODE_409);
        }
        JSONObject jsonObj = JSONObject.fromObject(rowData);
        String email = (String) jsonObj.get("email");
        String userId = (String) jsonObj.get("userId");
        if (StringUtils.isEmpty(email))
        {
            logger.error("->email is empty,email:{} ", email);
            return ResultUtil.error(ResultEnum.CODE_409);
        }
        if (StringUtils.isEmpty(userId))
        {
            logger.error("->userId is empty,userId:{} ", userId);
            return ResultUtil.error(ResultEnum.CODE_410);
        }
        int update = emailMapper.deleteByEmail(email, userId);
        if (update >= 1)
        {
            return ResultUtil.success();
        }
        return ResultUtil.error(ResultEnum.CODE_422);
    }

    @Override
    public Result findUserInfo(String userId)
    {
        logger.info("->The user enter service findUserInfo param is rowData:{}", userId);
        if (StringUtils.isEmpty(userId))
        {
            logger.error("->userId is empty,userId:{} ", userId);
            return ResultUtil.error(ResultEnum.CODE_410);
        }
        User user = userMapper.findByUserId(userId);
        if (null == user)
        {
            logger.error("->userId error, the request info is：" + userId);
            return ResultUtil.error(ResultEnum.CODE_409);
        }
        user.setOpenId(null);
        return ResultUtil.OTSResult(user);
    }

    @SuppressWarnings("unused")
    @Override
    public Result updateUserInfo(User rowData)
    {
        logger.info("->The user enter service updateUserInfo param is rowData:{}",
                    rowData.toString());
        if (rowData == null)
        {
            logger.error("->rowData is empty,rowData:{} ", rowData.toString());
            return ResultUtil.error(ResultEnum.CODE_409);
        }
        int i = userMapper.updateByPrimaryKeySelective(rowData);
        if (i > 0)
        {
            logger.info("用户信息修改成功：｛｝" + i);
            return ResultUtil.success();
        }
        else
        {
            logger.error("->用户信息修改失败,rowData: " + rowData.toString());
            return ResultUtil.error(ResultEnum.CODE_423);
        }
    }

    @Override
    public Result findEmailById(String id)
    {
        logger.info("->The user enter service findEmailById param is id:{}", id);
        if (StringUtils.isEmpty(id))
        {
            logger.error("->id is empty,id:{} ", id);
            return ResultUtil.error(ResultEnum.CODE_409);
        }
        Email email = emailMapper.findEmailById(id);
        if (email != null)
        {
            return ResultUtil.OTSResult(email);
        }
        logger.error("->Id error, the request info is：" + id);
        return ResultUtil.error(ResultEnum.CODE_409);
    }

    @SuppressWarnings("unused")
    @Override
    public Result UpdateEmail(Email rowData)
    {
        logger.info("->The user enter service UpdateEmail param is rowData:{}", rowData.toString());
        if (null == rowData)
        {
            logger.error("->rowData is empty,rowData:{} ", rowData.toString());
            return ResultUtil.error(ResultEnum.CODE_409);
        }
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        rowData.setUpdateTime(formatter.format(new Date()));
        Email email = emailMapper.findEmailById(rowData.getId());
        if (!rowData.getEmail().equals(email.getEmail()))
        {
            // Redis验证码
            String email1 = rowData.getEmail();
            String checkCode = rowData.getCheckCode();
            boolean bool = redisWrapUtil.check(email1, checkCode);
            if (!bool)
            {
                return ResultUtil.error(ResultEnum.CODE_403);
            }
        }
        int i = emailMapper.updateByExampleSelective(rowData);
        if (i > 0)
        {
            logger.info("邮箱信息修改成功：｛｝" + i);
            return ResultUtil.success();
        }
        else
        {
            logger.error("->用户信息修改失败,rowData: " + rowData.toString());
            return ResultUtil.error(ResultEnum.CODE_423);

        }
    }

}
		     
		    
	 
	

